package org.phalanx.server.game;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;

import org.phalanx.map.MapTileSet;
import org.phalanx.map.PhalanxMap;
import org.phalanx.map.PhalanxMapReader;
import org.phalanx.map.PhalanxTileSetReader;
import org.phalanx.server.ServerCache.AbstractCacheHandler;
import org.phalanx.server.ServerCache.Cache;
import org.phalanx.server.ServerCache.Cacheable;

public class PhalanxMapCacheHandler implements AbstractCacheHandler {
	private String cacheDir;
	private MapTileSet defaultTileSet;
	private String mapsDir;
	
	public PhalanxMapCacheHandler(String mapsDir, String defaultTileSetPath, String cacheDir, PhalanxMapManager mapMgr){
		this.cacheDir = cacheDir;
		this.mapsDir = mapsDir;
		
		mapMgr.setDefaultTileSet(readInDefaultTileSet(defaultTileSetPath));
	}
	
	private MapTileSet readInDefaultTileSet(String defaultTileSetPath){
		PhalanxTileSetReader p = new PhalanxTileSetReader();
		defaultTileSet = new MapTileSet();
		boolean isSuccess;
		
		try {
			String defaultTileSetFileName = defaultTileSetPath;
			p.setTerrainFileByName(defaultTileSetFileName);
			isSuccess = p.readInTerrain();
			if (isSuccess){
				defaultTileSet = p.getMapTileSet();
				defaultTileSet.setTileSetArchiveFile(defaultTileSetFileName);
				defaultTileSet.setCanonicalFilePath(defaultTileSetFileName);
			}
			
		} catch (IOException ie){}
		
		return defaultTileSet;
	}
	
	@Override
	public boolean addElementToDB(Cache c, Object newKey, Cacheable newElement) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean deleteObjectFromDB(Cache c, Object newKey,
			Cacheable newElement) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public ArrayList<Cacheable> getMultipleObjectsFromDB(Cache c,
			Object newKey, boolean cacheUpdate) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Cacheable getObjectFromDB(Cache c, Object newKey, boolean cacheUpdate) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public boolean populateCache(Cache c) {
		PhalanxMapReader reader = new PhalanxMapReader(defaultTileSet,cacheDir);
		
		File mapsDirObj = new File(mapsDir);

		String[] mapList = mapsDirObj.list();
		
		ArrayList<PhalanxMap> test = new ArrayList<PhalanxMap>();
		
		if (mapList.length > 0){
			for (int i = 0; i < mapList.length; i++){
				reader = new PhalanxMapReader(defaultTileSet,cacheDir);
				reader.setMapFileByName(mapsDir + mapList[i]);
				reader.readInMapData();
				PhalanxMap pMap = new PhalanxMap();
				pMap = reader.getMap();
				
				test.add(pMap);
				
				if (pMap != null && pMap.getMapName() != null){
					c.put(pMap.getMapName(), new PhalanxMapCacheWrapper(reader.getMap()));
				}
			}
		}
		return false;
	}

	@Override
	public boolean updateElementToDB(Cache c, Object newKey,
			Cacheable newElement) {
		// TODO Auto-generated method stub
		return false;
	}

}
